#!/usr/bin/env python
# encoding: utf-8

import serial
import serial.tools.list_ports
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from ui.comSet import Ui_Form
import configparser
import os

class ComSetWidget(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle("设置默认通信串口")
        self.listView.clicked.connect(self.listViewClicked)
        self.pushButton_set.clicked.connect(self.setDefaultCom)
        self.pushButton_update.clicked.connect(self.findCom)
        # 当前串口
        self.current_port = None
        self.port_list = []

    def findCom(self):
        """查询所有串口"""
        port_list = list(serial.tools.list_ports.comports())
        self.port_list = port_list
        self.qList = [str(p.device) for p in self.port_list]
        # 设置模型列表视图，加载数据列表
        slm = QStringListModel()
        slm.setStringList(self.qList)
        # 设置列表视图的模型
        self.listView.setModel(slm)

    def listViewClicked(self, qModelIndex):
        """点击显示串口详细信息"""
        p = self.port_list[qModelIndex.row()]
        self.current_port = p
        txt = "device: %s\r\n" \
              "description: %s\r\n" \
              "hwid: %s\r\n" \
              "serial_number: %s\r\n" \
              "manufacturer: %s\r\n" % (
              p.device, p.description, p.hwid, p.serial_number, p.manufacturer)
        self.textBrowser.setText(txt)

    def setDefaultCom(self):
        """设置默认串口"""
        try:
            p = self.current_port
            config = configparser.RawConfigParser()
            # 添加condition选项
            config.add_section('com')
            config.set("com", "device", str(p.device))
            config.set("com", "description", str(p.description))
            config.set("com", "hwid", str(p.hwid))
            config.set("com", "serial_number", str(p.serial_number))
            config.set("com", "manufacturer", str(p.manufacturer))
            config.set("com", "baudrate", self.comboBox_baudrate.currentText())
            # 文件名称
            filename = os.getcwd()+"/conf/com.ini"
            # 写入并保存文件到当前项目文件夹下
            with open(filename, 'w') as configfile:
                config.write(configfile)
            QMessageBox.warning(self, "提示", "设置%s为默认通信串口！"%p.device, QMessageBox.Yes)
        except Exception as e:
            QMessageBox.warning(self,"错误","%s"%e, QMessageBox.Yes)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    window = ComSetWidget()
    window.show()
    app.exec_()
